package Socket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

//封装了TCP协议的通信细节，可以和服务端建立通信联系，并且基于两条流（输入，输出）实现交互
//可以当做电话
/*
    聊天室客户端
 */
public class Client {
    private Socket socket;

    public Client(){
        /*
        实例化socket,就是和远程计算机建立连接的过程
        需要传入两个参数，一个ip地址，一个端口号
         */
        try {
            System.out.println("连接服务器中...");
            socket = new Socket("localhost",8088);
            System.out.println("连接成功！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void Start(){
        /*

         */
        try {
                //启动一个线程来负责读取服务端发送过来的消息
                serverHandler serverHandler = new serverHandler();
                Thread t = new Thread(serverHandler);
                t.setDaemon(true);
                t.start();

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter pw = new PrintWriter(bw,true);

                Scanner scan = new Scanner(System.in);
                System.out.println("我要说话了：");
            while (true) {
                String line = scan.nextLine();
                if ("exit".equals(line)){
                    break;
                }
                pw.println("用户端说："+line);

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try{
                /*
                 socket的close方法回将通过它获取的流关闭，并且会向
                 */
                socket.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.Start();
    }
    //读取服务端发送过来的消息
    private class serverHandler implements Runnable{
        @Override
        public void run() {
            try{
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String line;
                System.out.println("说话：");
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
